<template>
  <div class="price-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :disabled="mode === 'view'"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" header="基本信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品" prop="productId">
              <el-select
                v-model="formData.productId"
                placeholder="请选择商品"
                filterable
                style="width: 100%"
                @change="handleProductChange"
              >
                <el-option
                  v-for="product in productList"
                  :key="product.id"
                  :label="`${product.code} - ${product.name}`"
                  :value="product.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格类型" prop="priceType">
              <el-select v-model="formData.priceType" placeholder="请选择价格类型" style="width: 100%">
                <el-option label="阶梯价格" value="tiered" />
                <el-option label="批量折扣" value="bulk" />
                <el-option label="季节性价格" value="seasonal" />
                <el-option label="促销价格" value="promotion" />
                <el-option label="VIP价格" value="vip" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户等级" prop="customerLevel">
              <el-select v-model="formData.customerLevel" placeholder="请选择客户等级" style="width: 100%">
                <el-option label="VIP" value="VIP" />
                <el-option label="一级" value="一级" />
                <el-option label="二级" value="二级" />
                <el-option label="三级" value="三级" />
                <el-option label="普通" value="普通" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="生效" value="active" />
                <el-option label="待生效" value="pending" />
                <el-option label="已失效" value="expired" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 价格设置 -->
      <el-card class="form-section" header="价格设置">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="基础价格" prop="basePrice">
              <el-input-number
                v-model="formData.basePrice"
                :min="0"
                :precision="2"
                placeholder="请输入基础价格"
                style="width: 100%"
                @change="calculateFinalPrice"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣率(%)" prop="discountRate">
              <el-input-number
                v-model="formData.discountRate"
                :min="0"
                :max="100"
                :precision="2"
                placeholder="请输入折扣率"
                style="width: 100%"
                @change="calculateFinalPrice"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最终价格" prop="finalPrice">
              <el-input-number
                v-model="formData.finalPrice"
                :min="0"
                :precision="2"
                placeholder="最终价格"
                style="width: 100%"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小数量" prop="minQuantity">
              <el-input-number
                v-model="formData.minQuantity"
                :min="1"
                placeholder="请输入最小数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 阶梯价格设置 -->
      <el-card class="form-section" header="阶梯价格设置" v-if="formData.priceType === 'tiered'">
        <div class="tier-price-header">
          <span>价格阶梯</span>
          <el-button type="primary" size="small" @click="addTierPrice" :icon="Plus">添加阶梯</el-button>
        </div>
        <el-table :data="formData.tierPrices" border style="width: 100%; margin-top: 10px;">
          <el-table-column label="最小数量" width="150">
            <template #default="{ row, $index }">
              <el-input-number
                v-model="row.minQuantity"
                :min="1"
                placeholder="最小数量"
                style="width: 100%"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="最大数量" width="150">
            <template #default="{ row, $index }">
              <el-input-number
                v-model="row.maxQuantity"
                :min="row.minQuantity || 1"
                placeholder="最大数量"
                style="width: 100%"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" width="150">
            <template #default="{ row, $index }">
              <el-input-number
                v-model="row.price"
                :min="0"
                :precision="2"
                placeholder="单价"
                style="width: 100%"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="折扣率(%)" width="150">
            <template #default="{ row, $index }">
              <el-input-number
                v-model="row.discountRate"
                :min="0"
                :max="100"
                :precision="2"
                placeholder="折扣率"
                style="width: 100%"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                @click="removeTierPrice($index)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 有效期设置 -->
      <el-card class="form-section" header="有效期设置">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="formData.effectiveDate"
                type="date"
                placeholder="选择生效日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期" prop="expiryDate">
              <el-date-picker
                v-model="formData.expiryDate"
                type="date"
                placeholder="选择失效日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 适用条件 -->
      <el-card class="form-section" header="适用条件">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="适用地区" prop="applicableRegions">
              <el-select
                v-model="formData.applicableRegions"
                multiple
                placeholder="请选择适用地区"
                style="width: 100%"
              >
                <el-option label="全国" value="全国" />
                <el-option label="华北" value="华北" />
                <el-option label="华东" value="华东" />
                <el-option label="华南" value="华南" />
                <el-option label="华中" value="华中" />
                <el-option label="西北" value="西北" />
                <el-option label="西南" value="西南" />
                <el-option label="东北" value="东北" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用渠道" prop="applicableChannels">
              <el-select
                v-model="formData.applicableChannels"
                multiple
                placeholder="请选择适用渠道"
                style="width: 100%"
              >
                <el-option label="线上" value="online" />
                <el-option label="线下" value="offline" />
                <el-option label="批发" value="wholesale" />
                <el-option label="零售" value="retail" />
                <el-option label="代理" value="agent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小订单金额" prop="minOrderAmount">
              <el-input-number
                v-model="formData.minOrderAmount"
                :min="0"
                :precision="2"
                placeholder="请输入最小订单金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否可叠加" prop="stackable">
              <el-switch
                v-model="formData.stackable"
                active-text="可叠加"
                inactive-text="不可叠加"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 审批信息 -->
      <el-card class="form-section" header="审批信息" v-if="mode !== 'add'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人">
              <el-input v-model="formData.applicant" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请时间">
              <el-input v-model="formData.applyTime" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="formData.status !== 'pending'">
          <el-col :span="12">
            <el-form-item label="审批人">
              <el-input v-model="formData.approver" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间">
              <el-input v-model="formData.approveTime" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions" v-if="mode !== 'view'">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        {{ mode === 'add' ? '创建价格' : '更新价格' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  priceData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'add', // add, edit, view
    validator: (value) => ['add', 'edit', 'view'].includes(value)
  }
})

// Emits
const emit = defineEmits(['save', 'cancel'])

// 响应式数据
const formRef = ref()
const saving = ref(false)

// 商品列表
const productList = ref([
  { id: 1, code: 'P001', name: '苹果iPhone 15', basePrice: 6999 },
  { id: 2, code: 'P002', name: '华为Mate 60', basePrice: 5999 },
  { id: 3, code: 'P003', name: '小米14 Pro', basePrice: 4999 },
  { id: 4, code: 'P004', name: 'OPPO Find X7', basePrice: 4599 },
  { id: 5, code: 'P005', name: 'vivo X100', basePrice: 3999 }
])

// 表单数据
const formData = reactive({
  id: null,
  productId: null,
  productCode: '',
  productName: '',
  priceType: '',
  customerLevel: '',
  basePrice: 0,
  discountRate: 0,
  finalPrice: 0,
  minQuantity: 1,
  effectiveDate: '',
  expiryDate: '',
  applicableRegions: [],
  applicableChannels: [],
  minOrderAmount: 0,
  stackable: false,
  status: 'pending',
  tierPrices: [],
  applicant: '',
  applyTime: '',
  approver: '',
  approveTime: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  priceType: [{ required: true, message: '请选择价格类型', trigger: 'change' }],
  customerLevel: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
  basePrice: [{ required: true, message: '请输入基础价格', trigger: 'blur' }],
  discountRate: [{ required: true, message: '请输入折扣率', trigger: 'blur' }],
  minQuantity: [{ required: true, message: '请输入最小数量', trigger: 'blur' }],
  effectiveDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
  expiryDate: [{ required: true, message: '请选择失效日期', trigger: 'change' }]
}

// 方法
const handleProductChange = (productId) => {
  const product = productList.value.find(p => p.id === productId)
  if (product) {
    formData.productCode = product.code
    formData.productName = product.name
    formData.basePrice = product.basePrice
    calculateFinalPrice()
  }
}

const calculateFinalPrice = () => {
  if (formData.basePrice && formData.discountRate >= 0) {
    formData.finalPrice = formData.basePrice * (1 - formData.discountRate / 100)
    formData.finalPrice = Math.round(formData.finalPrice * 100) / 100
  }
}

const addTierPrice = () => {
  formData.tierPrices.push({
    minQuantity: 1,
    maxQuantity: null,
    price: 0,
    discountRate: 0
  })
}

const removeTierPrice = (index) => {
  formData.tierPrices.splice(index, 1)
}

const disabledDate = (time) => {
  if (!formData.effectiveDate) return false
  return time.getTime() < new Date(formData.effectiveDate).getTime()
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    // 验证阶梯价格
    if (formData.priceType === 'tiered' && formData.tierPrices.length === 0) {
      ElMessage.warning('阶梯价格类型需要设置价格阶梯')
      return
    }
    
    saving.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    emit('save', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

const initFormData = () => {
  if (props.priceData) {
    Object.assign(formData, props.priceData)
    if (!formData.tierPrices) {
      formData.tierPrices = []
    }
    if (!formData.applicableRegions) {
      formData.applicableRegions = []
    }
    if (!formData.applicableChannels) {
      formData.applicableChannels = []
    }
  } else {
    // 新增模式，设置默认值
    formData.status = 'pending'
    formData.minQuantity = 1
    formData.discountRate = 0
    formData.stackable = false
    formData.tierPrices = []
    formData.applicableRegions = []
    formData.applicableChannels = []
    formData.applicant = '当前用户'
    formData.applyTime = new Date().toLocaleString()
  }
}

// 监听器
watch(() => props.priceData, () => {
  initFormData()
}, { immediate: true })

watch(() => formData.priceType, (newType) => {
  if (newType !== 'tiered') {
    formData.tierPrices = []
  } else if (formData.tierPrices.length === 0) {
    addTierPrice()
  }
})

// 生命周期
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.price-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
}

.tier-price-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: bold;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.form-actions .el-button {
  margin-left: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .price-form {
    max-height: 60vh;
  }
  
  .tier-price-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .form-actions {
    text-align: center;
  }
  
  .form-actions .el-button {
    margin: 0 6px;
  }
}
</style>